<script setup lang="ts">
import { create, PhotoPage, DeletePhotographer, update } from "@/apis/cameraman"
import { ref, reactive, onMounted } from 'vue'
import { v4 as uuidv4 } from 'uuid';
import { getHomeMulidata, putsaveMediaData } from '@/apis/uploadApi'
import { Upload, DeleteFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import { fa } from "element-plus/es/locale";
let dialogVisible = ref(false)
let photographerList = ref([])
let tagList = reactive([])
let title = ref('修改摄影师信息')
let PhotomanId = ref('')
let massage = ref('')
let totals = ref()
const url = ref('')

let uploadrefss = ref('');
const formRef = ref(null);
// 头像url
let hederurl = ref('')
let formInline = reactive({
    name: '',
    post: '',
    tags: '',
    introduction: '',
    remark: '',
    sort: '',
    sex: '',
    status: '',
    recommendHot: ''
})
const options = [
    {
        value: '男',
        label: '男',
    }, {
        value: '女',
        label: '女',
    }
]
const options1 = [
    {
        value: '可用',
        label: '可用',
    }, {
        value: '不可用',
        label: '不可用',
    }
]
const options2 = [
    {
        value: '是',
        label: '是',
    }, {
        value: '否',
        label: '否',
    }
]
// 校验规则
const rules = ref({
    name: [
        { required: true, message: '摄影师姓名是必填项', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '摄影师性别是必填项', trigger: 'change' },
    ],
    status: [
        { required: true, message: '摄影师状态是必填项', trigger: 'change' },
    ],
    introduction: [
        { required: true, message: '摄影师简介是必填项', trigger: 'blur' },
        { max: 70, message: '摄影师简介最多70个字', trigger: 'blur' },
    ],
    remark: [
        { required: false, message: '请填写备注', trigger: 'blur' },
        { max: 10, message: '备注最多10个字', trigger: 'blur' },
    ],
    sort: [
        { required: true, message: '摄影师排序是必填项', trigger: 'blur' },
        { type: 'number', message: '摄影师排序必须为数字', trigger: 'blur' },
    ],
    recommendHot: [
        { required: true, message: '是否推荐摄影师是必填项', trigger: 'change' },
    ],
    // 其他规则...
});
// 获取加载页面的摄影师信息
onMounted(
    getPhotoPage
)
async function getPhotoPage() {
    const res = await PhotoPage({
        "pageNo": 1,
        "pageSize": 8
    })
    photographerList.value = res.data.list
    totals = Number(res.data.total)
    // 访问 tags 字符串
    for (let i = 0; i < res.data.list.length; i++) {
        const tagsString = res.data.list[i].tags
        tagList = tagsString
    }
}

// 上传头像
// 文件提交
async function toUpload(action) {
    const file = action.file; // 获取文件扩展名
    const fileName = file.name
    const fileExtension = fileName.split('.').pop(); // 获取文件扩展名
    // 生成 UUID 并将其添加到文件名中
    const uuid = uuidv4();
    const newFileName = `${uuid}.${fileExtension}`;

    const fileSizeInBytes = file.size;
    const mimeType = file.type;
    // // 格式化文件大小为可读的字符串，例如 "150 KB", "3.2 MB" 等
    // function formatFileSize(bytes, decimals = 2) {
    //     if (bytes === 0) return '0 Bytes';
    //     const k = 1024;
    //     const dm = decimals < 0 ? 0 : decimals;
    //     const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    //     const i = Math.floor(Math.log(bytes) / Math.log(k));
    //     return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    // }
    // const formattedFileSize = formatFileSize(fileSizeInBytes);

    try {

        // 发送请求到后端接口，获取预签名URL
        const res = await getHomeMulidata(newFileName, fileSizeInBytes);
        await axios.put(res.data.uploadUrl, action.file, {
            headers: {
                'Content-Type': file.type
            }
        })
        hederurl = res.data.url
        formInline.post = res.data.url
        if (res.data.url != '') {
            ElMessage.success('上传头像成功')
        }
        // {
        //     "configId": 11,
        //     "path": newFileName,
        //     "name": fileName,
        //     "url": res.data.url,
        //     "type": "application/octet-stream",
        //     "size": 2048,
        //     "fileId": 0,
        //     "description": "image",
        //     "authorId": 123
        // }
    } catch (error) {
        console.error('Upload error:', error);
    }
}
// 提交按钮
async function submit() {
    formRef.value.validate(async (valid) => {
        if (valid) {
            if (title.value === '添加摄影师') {
                console.log(formInline.sex);
                console.log(formInline.status);
                console.log(formInline.recommendHot);

                const mitData = {
                    "name": formInline.name,
                    "sex": formInline.sex === '男' ? 1 : 2,
                    "post": formInline.post,
                    "tags": formInline.tags,
                    "status": formInline.status === '可用' ? 1 : 2,
                    "introduction": formInline.introduction,
                    "remark": formInline.remark,
                    "sort": formInline.sort,
                    "recommendHot": formInline.recommendHot == 'false' ? false : true,
                }
                try {
                    const res = await create(mitData)
                    if (res.code == 0) {
                        ElMessage.success('添加摄影师成功')
                        getPhotoPage()
                    } else {
                        ElMessage.error(res.data.msg)
                    }
                } catch (error) {
                    ElMessage.error(error)

                } finally {
                    dialogVisible.value = false;
                }
            } else if (title.value === '修改摄影师信息') {
                const updateData = {
                    "id": PhotomanId,
                    "name": formInline.name,
                    "sex": formInline.sex === '男' ? 1 : 2,
                    "post": formInline.post,
                    "tags": formInline.tags,
                    "status": formInline.status === '可用' ? 1 : 2,
                    "introduction": formInline.introduction,
                    "remark": formInline.remark,
                    "sort": formInline.sort,
                    "recommendHot": formInline.recommendHot === '是' ? true : false,
                }
                try {
                    const res = await update(updateData)
                    if (res.code == 0) {
                        ElMessage.success('修改摄影师成功')
                        getPhotoPage()
                    } else {
                        ElMessage.error(res.data.msg)
                    }
                } catch (err) {
                    console.log(err);

                } finally {
                    dialogVisible.value = false;
                }
            }
        } else {
            ElMessage.error('表单校验失败')
            return false
        }
    })

    // 发送请求的代码...
    // const tage = formInline.label.split('，')
    // const tagsString = `[${tage.map(tag => `"${tag}"`).join(',')}]`;


}
// 修改摄影师
async function modification(item) {
    console.log(item);
    formInline.name = item.name
    formInline.post = item.post
    formInline.tags = item.tags
    formInline.introduction = item.introduction
    formInline.remark = item.remark
    formInline.sort = item.sort
    formInline.sex = item.sex == 1 ? '男' : '女'
    formInline.status = item.status == 1 ? '可用' : '不可用'
    formInline.recommendHot = item.recommendHot === true ? '是' : '否'
    PhotomanId = item.id
}
// 删除摄影师
async function toDownload(item) {
    ElMessageBox.confirm(
        '确定要删除该摄影师吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await DeletePhotographer(item.id)
            massage.value = res.msg
            if (res.code == 0) {
                ElMessage.success('删除摄影师成功')
                getPhotoPage()
            } else {
                ElMessage.error(res.msg)
            }
        })
        .catch(() => {
            ElMessage({
                type: 'error',
                message: massage.value,
            })
        })
}
// 关闭前的回调
function handleCLose() {
    dialogVisible.value = false
}
function handleSizeChange(val: number) {
    console.log(`${val} items per page`)

}
async function handleCurrentChange(val: number) {
    const res = await PhotoPage({
        "pageNo": val,
        "pageSize": 8
    })
    photographerList.value = res.data.list
    totals = res.data.total
    // 访问 tags 字符串
    for (let i = 0; i < res.data.list.length; i++) {
        const tagsString = res.data.list[i].tags;

        tagList = tagsString
    }

}
function addpictureMan() {
    dialogVisible.value = true
    title.value = '添加摄影师'
    formInline.name = ''
    formInline.post = ''
    formInline.tags = ''
    formInline.introduction = ''
    formInline.remark = ''
    formInline.sort = ''
    formInline.sex = ''
    formInline.status = ''
    formInline.recommendHot = ''
    uploadrefss.value.clearFiles()
}
</script>
<template>
    <div class="button">
        <el-button type="primary" @click="addpictureMan"> + 添加摄影师</el-button>
    </div>
    <div class="photographer">
        <div class="imagebox" v-for="(item, index) in photographerList" :key="index">
            <el-card>
                <div>
                    <div class="namebox">
                        <img style="width: 100%;height: 130px;" :src=item.post alt="">
                    </div>
                    <div>
                        <div>名称：{{ item.name }}</div>
                        <div>性别：{{ item.sex == 1 ? '男' : '女' }}</div>
                        <div>状态：{{ item.status == 1 ? '空闲' : '忙碌' }}</div>
                        <div>标签：
                            <div class="tags" v-for="tags in tagList = item.tags.split('，')" :key="tags">
                                {{ tags }}
                            </div>
                        </div>
                        <div class="jianjie">简介：{{ item.introduction }}</div>
                        <div style="width: 100%;height: auto;max-height: 100%;">备注：{{ item.remark }}</div>
                    </div>
                </div>
                <div class="menu">
                    <div class="icon">
                        <el-icon style="color: black;margin-left: 40%;" @click="toDownload(item)">
                            <DeleteFilled />
                        </el-icon>
                        <el-icon style="color: black;margin-left: 50px;"
                            @click="modification(item), dialogVisible = true, title = '修改摄影师信息'">
                            <Upload />
                        </el-icon>
                        <div class="namebox">
                            <img style="width: 100px;height: 100px;border-radius: 50%;margin-left: 5px;" :src=item.post
                                alt="">
                            <div style="margin-left: 20px;">
                                <div style="color: white;">名称：{{ item.name }}</div>
                                <div style="color: white;">性别：{{ item.sex == 1 ? '男' : '女' }}</div>
                                <div style="color: white;">状态：{{ item.status == 1 ? '空闲' : '忙碌' }}</div>
                            </div>
                        </div>

                        <div style="color: white;margin-left: 5px;margin-right:5px;margin-top: 10px ">标签：
                            <div class="tag" v-for="tags in tagList = item.tags.split('，')" :key="tags">
                                {{ tags }}
                            </div>
                        </div>
                        <div
                            style="width: 100%;height: auto;max-height: 100%;color: white;margin-left: 5px;margin-right:5px;">
                            简介：{{
            item.introduction }}
                        </div>
                        <div
                            style="width: 100%;height: auto;max-height: 100%;color: white;margin-left: 5px;margin-right:5px;">
                            备注：{{
            item.remark }}</div>
                    </div>
                </div>
            </el-card>
        </div>
        <div style="width: 100%; height: 80px;">
            <div class="example-pagination-block">
                <el-pagination layout="prev, pager, next" :total='totals' :page-size='8' @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close=handleCLose>
        <div>
            <el-form :inline="true" :model="formInline" class="demo-form-inline" size="large" ref="formRef"
                :rules="rules">
                <el-form-item label="摄影师姓名" prop="name">
                    <el-input v-model="formInline.name" placeholder="请填写摄影师姓名" />
                </el-form-item>
                <el-form-item label="摄影师性别" prop="sex">
                    <el-select v-model="formInline.sex" placeholder="请选择摄影师性别" size="large" style="width: 240px">
                        <el-option v-for=" item  in  options " :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="摄影师头像">
                    <el-upload class="upload-demo" :http-request="toUpload" accept="image/*" ref="uploadrefss">
                        <el-button type="primary">点击上传</el-button>
                        <template #tip>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="摄影师标签" prop="tags">
                    <el-input v-model="formInline.tags" placeholder="添加摄影师标签(用 ，隔开)" />
                </el-form-item>
                <el-form-item label="摄影师状态" required prop="status">
                    <el-select v-model="formInline.status" placeholder="请选择摄影师状态" size="large" style="width: 240px">
                        <el-option v-for=" item  in  options1 " :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="摄影师简介" prop="introduction">
                    <el-input v-model="formInline.introduction" placeholder="请填写摄影师简介" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formInline.remark" placeholder="请填写备注" />
                </el-form-item>
                <el-form-item label="摄影师排序" prop="sort">
                    <el-input v-model.number="formInline.sort" placeholder="摄影师排序(值越大越靠前)" />
                </el-form-item>
                <el-form-item label="是否推荐摄影师" prop="recommendHot">
                    <el-select v-model="formInline.recommendHot" placeholder="请选择是否推荐摄影师" size="large"
                        style="width: 240px">
                        <el-option v-for=" item  in  options2 " :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCLose">取消</el-button>
                <el-button type="primary" @click="submit">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style scoped>
.imagebox {
    width: 300px;
    height: 320px;
    margin: 20px 50px 1px 60px;
    position: relative;
}

.button {
    width: 100%;
    height: 50px;
}

.jianjie {
    width: 100%;
    height: auto;
    white-space: nowrap;
    /* 文本不换行 */
    overflow: hidden;
    /* 隐藏超出部分 */
    text-overflow: ellipsis;
    /* 超出部分用省略号表示 */
}

.example-pagination-block {
    margin-left: 75%;
    margin-top: 1%;
    position: absolute;
}

.menu {
    margin-left: -20px;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(to right top,
            /* 渐变方向：从左到右 */

            #b1d7ff,
            #409eff
            /* 起始颜色 */

            /* 结束颜色 */
        );

    /* 完全透明，白色基础 */
    display: none;
    cursor: pointer;
    transition: transform 0.5s ease-in-out;
    opacity: 0.5;
    /* 初始透明度 */
    transform: scale(1);
    /* 初始缩放比例 */
    transition: transform 0.8s ease, opacity 0.8s ease;
}

.menu:hover {
    opacity: 1;
    /* 鼠标悬停时的透明度 */
    transform: scale(1.1);
    /* 鼠标悬停时的缩放比例 */
}


/* 可能需要写在menu上面 */
.imagebox:hover .menu {
    display: block;
}

.photographer {
    position: reactive;
    background-color: #f8f9fc;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    margin: 10px 20px;
    flex-wrap: wrap;
    height: 700px;
}

.namebox {
    display: flex;
    padding: 20px auto;
}

.tag {
    display: inline-block;
    background-image: linear-gradient(to right,
            #a2d0ff,
            #fff);
    margin-left: 10px;
    padding: 3px 15px;
    color: gray;
    border-radius: 10% 10% 10% 10%;
    font-size: 10px;
}

.tags {
    display: inline-block;
    background-image: linear-gradient(to right,
            #a2d0ff,
            #409eff);
    margin-left: 5px;
    padding: 3px 15px;
    border-radius: 0 10% 0 10%;
    font-size: 10px;
}

.el-popper-container {
    display: flex;
    margin-top: 10px;
}
</style>